# -*- coding: utf-8 -*-
# @Date：2024/7/18 17:46:49
# @Author：CJiaの青姝
# @FileName：userinfo
# @Editor：PyCharm2024
# @Remark：
from django.core.cache import cache
from config.env import REDIS_DEPLOY
from backend.settings import WHITE_USER_LIST
from auths.models import Users, UsersToken, UsersRole
from system.models import MenuButton, RoleMenuItem
from utils.cj_jwt import decode_token
from utils.serializes import model_serialize_obj


def get_user_info_from_token(request):
    token = request.META.get("HTTP_AUTHORIZATION")
    if token is None:
        return None
    token = token.replace("Bearer ", "")
    payload = decode_token(token, UsersToken)
    user_info = Users.objects.get(id=payload['data']['id'])
    # 用户信息序列化
    user = model_serialize_obj(user_info)
    if user['username'] in WHITE_USER_LIST:
        user['is_superuser'] = True
    else:
        user['is_superuser'] = False
    role_ids = UsersRole.objects.filter(user_id=user['id']).values_list('role_id', flat=True)
    user['roles'] = list(role_ids)  # 当前全部角色
    menu_button_ids = RoleMenuItem.objects.filter(role_id__in=role_ids).values_list('menu_button_id', flat=True)
    # 已配置权限列表
    user['permissions'] = list(MenuButton.objects.filter(id__in=menu_button_ids).values_list("code", flat=True))
    # 返回结果
    return user


def get_user_logout_token(request):
    authorization = request.META.get("HTTP_AUTHORIZATION")
    token = authorization.replace('Bearer ', "")  # 分割token
    # token解析结果
    result = decode_token(token, UsersToken)
    if REDIS_DEPLOY:
        # 刪除缓存
        cache.delete_pattern(result['data']["username"])
    UsersToken.objects.filter(username=result['data']['username']).delete()
    # 返回结果
    return "注销成功"
